package galaxy.kernel.component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ECSComponents {
    private Map<Class<? extends ECSComponent>, List<ECSComponent> > components = new LinkedHashMap<>();

    public ECSComponents add(ECSComponent component) {
        List<ECSComponent> cpts = components.get(component.getClass());
        if (cpts == null) {
            cpts = new ArrayList<>();
            components.put(component.getClass(), cpts);
        }
        cpts.add(component);
        return this;
    }

    public List<ECSComponent> get(Class<? extends ECSComponent> clazz){
        return components.get(clazz);
    }

    public <T extends ECSComponent> T getSingle(Class<? extends ECSComponent> clazz){
        List<ECSComponent> cpts = components.get(clazz);
        if (cpts == null||cpts.isEmpty()) {
            return null;
        }
        return (T) cpts.get(0);
    }

    public void delete(ECSComponent c) {
        List<ECSComponent> cpts = this.components.get(c.getClass());
        if (cpts==null) {
            return ;
        }
        int i = cpts.indexOf(c);
        if (i>=0) {
            cpts.remove(i);
        }
    }
}
